#include <errno.h>
#include <sstream>
#include <iostream>
#include <cstring>
#include "util.h"
#include "constants.h"

using namespace std;

void error(string message) {
	if (!message.empty()) {
		cerr << message << ": ";
	}
	cerr << strerror(errno) << endl;
}

void log(string message) {
	cout << message << endl;
}

vector<string> parse(const string &input, string separator) {
	size_t start = 0, next = 0;
	vector<string> v;
	while (start < input.size()) {
		next = input.find_first_of(separator, start);
		if (next == string::npos) {
			next = input.size();
		}
		if (start < next) {
			v.push_back(input.substr(start, next - start));
		}
		start = next + separator.length();
	}
	return v;
}

string get_error_message(int error_code) {
	stringstream ss;
	ss << error_code << ' ';
	switch (error_code) {
		case 0: ss << "Operation successful" << separator; break;
		case 100: ss << "Newline character found" \
				"outside of terminator" << separator; break;
				case 101: ss << "Malformed command" << separator; break;
				case 199: ss << "Internal server error" << separator; break;
				case 200: ss << "Command not recognized" << separator; break;
				case 201: ss << "Wrong arguments" << separator; break;
				case 202: ss << "File does not exist" << separator; break;
				case 203: ss << "Invalid position" << separator; break;
				default: ss << "Unknown error" << separator;
	}
	return ss.str();
}

bool is_reply_successful(string reply) {
	vector<string> result = parse(reply);
	return result.size() == 2 && result[0] == "0";
}

bool is_number(const std::string text) {
	for (size_t i = 0; i < text.length(); i++) {
		if (!isdigit(text[i])) {
			return false;
		}
	}
	return true;
}

string int_to_string(const int number) {
	stringstream ss;
	ss << number;
	return ss.str();
}

int string_to_int(const std::string string) {
	stringstream ss(string);
	int x;
	ss >> x;
	return x;
}

